#include "m_cmd_handle.h"
#include "m_cmd_decode.h"
#include "m_log.h"
#include "m_cmd_pass.h"

#include <stdio.h>

int m_cmd_handle(decode_result *result)
{
    int r;
    command cmd = {0};
    cmd.ackType = result->ackType;
    cmd.bizType = result->bizType;
    cmd.serialNo = result->serialNo;
    m_log_i(M_CMD_HANDLE_H, "cmd->ackType=%d,bizType=%d,serialNo=%d,", cmd.ackType, cmd.bizType, cmd.serialNo);
    if (result->ackType == M_CMD_REQ) {
        if (result->bizType == PASS) {
            cmd_req_pass pass = {0};
            pass.type = (result->buf[0] & 0xF0) >> 4;
            pass.route = (result->buf[0] & 0x0F);
            pass.size = result->size - 1;
            char buf_[pass.size];
            for (unsigned int i = 0; i < pass.size; i++) {
                *(buf_ + i) = *(result->buf + (1 + i));
            }
            pass.buf = &buf_;
            #ifdef M_LOG_INFO
            m_log_i(M_CMD_HANDLE_H, "pass->type=%d,route=%d\n", pass.type, pass.route);
            decode_data data = {pass.buf, pass.size, 0};
            decode_cache cache = {0};
            if (m_decode(&cache, &data, result) == 0) {
                m_cmd_handle(result);
            }
            #endif
            r = m_cmd_pass(pass);
            if (r != 0) {
                m_log_e(M_CMD_HANDLE_H, "cmd pass fail: %d\n", r);
                return 1;
            }
        } else if (result->bizType == ENJOY) {
            //cmd_req_enjoy enjoy = {0};
            #ifdef M_LOG_INFO
            unsigned int v = (unsigned int)result->buf[0];
            m_log_i(M_CMD_HANDLE_H, "enjoy->%s%s%s%s%s%s%s%s\n",
            (v & 0x80) ? "Left ":"",(v & 0x40) ? "Right ":"",(v & 0x20) ? "Up ":"",(v & 0x10) ? "Down ":"",
            (v & 0x08) ? "A ":"", (v & 0x04) ? "B ":"", (v & 0x02) ? "C ":"", (v & 0x01) ? "D ":"");
            #endif
        }
    }
}